Skip to main content

Alternatives to Inner Classes

Only had one place in the code where we created the iterator subclass and nowhere where its name is used. Might be annoying to keep creating a class each time we need one object somewhere in the code

  • An anonymous class is an inner class without a name.
  • Instead of giving a class a name and saying that the class extends/implements some class, name the super-class and then give the implementation of the changes.

Lambdas

  • Simpler syntax for an anonymous class when it sub classes : an interface which has only one method
  • Both of these are important!
  • Give it an implementation of the method
    • Only one method on the interface so it knows the method name
    • Knows the return type
    • Knows the parameters types
  • Use -> operator.
  • To the left of the -> are the parameters
  • To the right is the expression to evaluate to return the result value

Variable Capture

  • Lambda expressions can capture final(constant) variables from the surroundings. This kind of puts a copy of this variable inside the Lambda.
  • Can also use member variables, so it can capture the 'this' object

Expressions

Can think of them as a way of wrapping up a function in an object Once have an object, we keep an object reference to it Can use sub-type polymorphism and treat it as the base-class. Can access member variables or final local variables

Summary

If need an object to handle a function, could:

  • Create an object of a new top-level class
  • Create an object of an inner class
  • Create an object of an inner class
  • Create an object of an anonymous class
  • Create a Lambda